package com.songcha.module_bookreader.ui.activity.reader

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.text.InputType
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.songcha.module_bookreader.R
import com.songcha.module_bookreader.databinding.BookreaderActivityRead2Binding
import com.songcha.module_bookreader.event.ChapterSelectedEvent
import com.songcha.module_bookreader.manager.CacheManager
import com.songcha.module_bookreader.ui.fragment.slide.BookReadSlideFragment
import com.songcha.module_bookreader.ui.view.readview.BaseReadView
import com.songcha.module_bookreader.ui.view.readview.OverlappedReadWidget
import com.songcha.module_bookreader.ui.view.readview.Read3DWidget
import com.songcha.module_bookreader.ui.view.readview.TranslateReadWidget
import com.songcha.module_bookreader.utils.BookUtil
import com.songcha.module_bookreader.utils.FileUtils
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.bean.book.BookChapterCatalogBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.event.book.InBookShelfEvent
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.provider.IClearToMainActivityProvider
import com.songcha.library_business.provider.IDailyTaskProvider
import com.songcha.library_business.proxy.database.TodayWatchRewardAdvertCountDaoManager
import com.songcha.library_business.proxy.teenager.TeenagerManager
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.dialog.InputDialog
import com.songcha.library_common.ui.view.HeaderBarView
import com.songcha.library_common.util.ColorUtil
import com.songcha.library_common.util.FileUtil
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.StatusBarUtil
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.module_bookreader.BuildConfig
import com.songcha.module_bookreader.ui.view.BookReaderChapterAdvertContainerView
import com.songcha.module_bookreader.ui.view.readview.BaseReadView.IOnGetChapterAdvertView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit

@Route(path="/bookreader/BookReadActivity")
class BookReadActivity:BaseMvvmActivity<BookReadViewModel,BookreaderActivityRead2Binding>(),
    OnClickListener,SeekBar.OnSeekBarChangeListener,
    BaseReadView.IOnReadStateChangeListener,
    BaseReadView.IOnChapterAdvertListener {

    //private val mQueryWordDialog: QueryWordDialog? = null
    //private lateinit var mBookBean:BookBean
    //private val mOnWordStarProvider =
       // ARouter.getInstance().build("/sakura/WordStarImpl").navigation() as IOnWordStarProvider
    private var mStarWordList: List<String> = ArrayList()
    private var mIntentFilter: IntentFilter=IntentFilter()
    private var mReceiver = ReaderReceiver(this)
    private lateinit var mPageWidget: BaseReadView
    private var mBatteryLevel=100
    private var mIsDrawOnWord=false
    private lateinit var mCurrentBg:Bitmap
    private var mTeenagerInputPwdDialog:InputDialog?=null
    private var mSlideFrag:BookReadSlideFragment?=null
    private var mShowSetting=false
    //private var mIsShowBannerAdvertCloseBtn = false


    override fun getLayoutId(): Int {
        return R.layout.bookreader_activity_read2
    }

    override fun isNeedShowLoad(): Boolean {
        return true
    }

    override fun isNeedShowLoadingDialog(): Boolean {
        return true
    }

    override fun onRetry() {
        if(!this::mPageWidget.isInitialized) return
        //mPageWidget.onLoadSuccess()
        if(!viewModel.bookBean.isFromSDCard){
            viewModel.getBookChapterCatalog()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)

        //continue hide statusbar and navigationbar
        window.decorView.setOnSystemUiVisibilityChangeListener {
            if(it and (View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)==0){
                StatusBarUtil.fullScreen(this)
            }else{

            }
        }
    }

    @Subscribe
    fun onChapterSelected(event: ChapterSelectedEvent){
        if(event.chapter<1 || event.chapter>viewModel.chapterList!!.value!!.size) return
        viewModel.isJumpTo=true
        viewModel.jumpToChapter=event.chapter
        viewModel.getChapterContent(event.chapter)
        //databinding.bookreaderDrawer.closeDrawer(GravityCompat.END)
        databinding.bookreaderFlBottombar.visibility=View.GONE
        //databinding.bookreaderLlTopbar.visibility=View.GONE
        hideBar()
        databinding.includeSetting.bookreaderFlBottombarSetting.visibility=View.GONE
    }

    /*override fun onApplyWindowInsetsCall(v: View, insets: WindowInsetsCompat) {
        //set topbar margin
       databinding.bookreaderLlTopbar.layoutParams= databinding.bookreaderLlTopbar.layoutParams.apply {
           this as FrameLayout.LayoutParams
           topMargin=StatusBarUtil.getStatusBarHeight(this@BookReadActivity)
           if(!this@BookReadActivity::mPageWidget.isInitialized) return
           mPageWidget.setMarginTop(StatusBarUtil.getStatusBarHeight(this@BookReadActivity ) + HeaderBarView.DEFAULT_HEIGHT)
       }
    }*/

    override fun onRootViewPost() {
        //set topbar margin
        databinding.bookreaderLlTopbar.layoutParams= databinding.bookreaderLlTopbar.layoutParams.apply {
            this as FrameLayout.LayoutParams
            topMargin=StatusBarUtil.getStatusBarHeight(this@BookReadActivity)
            if(!this@BookReadActivity::mPageWidget.isInitialized) return
            mPageWidget.setMarginTop(StatusBarUtil.getStatusBarHeight(this@BookReadActivity ) + HeaderBarView.DEFAULT_HEIGHT)
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        StatusBarUtil.fullScreenForever(this)

        intent?.let {
            //mIsFromSD= it.getBooleanExtra("from_sdcard",false)
            //mFontPath= it.getStringExtra("font_path")?:""
            viewModel.bookBean=it.getParcelableExtra("book")?:return
            if(BuildConfig.DEBUG || viewModel.bookBean.isFromSDCard){
                viewModel.DEFAULT_FONTSIZE = 18
                viewModel.setDefaultFontSize()
            }
        }

        if(viewModel.bookBean == null){
            ToastUtil.show("无效的书籍")
            return
        }

        //databinding.bookreaderLlTopbar.setPadding(0,StatusBarUtil.getStatusBarHeight(this),0,0)

        //databinding.bookreaderTvTime.text=TimeUtil.formatTimeHHmm(System.currentTimeMillis())

        //get external chapter of jump direct
        intent?.let {
            viewModel.argChapter=intent.getIntExtra("chapter",0)
            viewModel.isFromDownload=intent.getBooleanExtra("from_download",false)
        }

        viewModel.getIsBookInShelf()
        viewModel.getReadProgress()
        viewModel.saveLastRead()

        setViewClickListener()
        databinding.includeSetting.bookreaderSeekbarBrightness.setOnSeekBarChangeListener(this)

        //initSlide()

        /*if(!viewModel.bookBean.isFromSDCard && FunctionConfig.IS_ADVERT_ENABLED && VarConfig.ADVERT_READER_BANNER_TYPE == VarConfig.ADVERT_TYPE_CSJ){
            initAdvert()
        }*/
        //TODO
        //loadBannerAdvert()

        //register battery and time change broadcast receiver
        mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED)
        mIntentFilter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(mReceiver, mIntentFilter)

        initAdvert()

        //direct open if local book
        if (viewModel.bookBean.isFromSDCard) {
            ViewHelper.setVisibility(false,databinding.bookreaderIvMenu)

            initSlide(mutableListOf())

            initPageWidget()

            //addLiveDataObserve()

            val srcFile = File(viewModel.bookBean.path)
            if(!srcFile.exists()){
                ToastUtil.show("本地书籍读取失败")
                return
            }

            for (i in 1..1) {
                val chapter = viewModel.bookBean.bookName
                //mChapterList.add(chapter)
                viewModel.addChapter(chapter)
                //add to cache directory
                val destFile = File(FileUtils.getChapterPath(viewModel.bookBean.id,i))
                if(BookUtil.isBookChapterFileExist(viewModel.bookBean.id,i)) continue
                val b = FileUtils.fileChannelCopy(
                    srcFile,
                    destFile
                )
            }
            //showChapterRead("",1,false,false,0,0)
            mPageWidget.onLoadSuccess()

        }else{

            showLoadingDialog(true)

            initPageWidget()

            //addLiveDataObserve()

            viewModel.getBookChapterCatalog()
            viewModel.chapterList.observe(this){data->
                if(data.size == 0) return@observe

                mPageWidget.setChapterList(viewModel.getChapterTitleList())

                initPageWidget()

                initSlide(data)

                hideLoadingDialog()

                if(viewModel.argChapter>0 && viewModel.argChapter<=data.size){
                    mPageWidget.jumpToChapter(viewModel.argChapter,true,0,0)
                }else{
                    viewModel.getChapterContent(viewModel.readProgress[0])
                }

            }

        }

    }

    private var mBannerAdvertCountDownDispose:Disposable? = null

    private fun initAdvert(){
        if(isShowBannerAdvert()){
            mBannerAdvertCountDownDispose?.dispose()
            mBannerAdvertCountDownDispose = Observable.interval(0,VarConfig.ADVERT_READER_BANNER_ADVERT_COUNTDOWN.toLong(), TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe{
                    if(!::mPageWidget.isInitialized) return@subscribe
                    if(mPageWidget.isChapterLastAdvertShowing) return@subscribe
                    loadBannerAdvert()
                }
        }
    }

    //private lateinit var mTTAdNative:TTAdNative
    //private var mTTAd:TTNativeExpressAd?=null
    //private var mAdSlot:AdSlot?=null

    override fun initObserver() {
        addLiveDataObserve()
    }

    private fun hideBannerAdvert(){
        ViewHelper.setVisibility(false,databinding.bookreaderFlAdvertParent)
        databinding.bookreaderFlAdvert.removeAllViews()
    }

    private fun isShowBannerAdvert():Boolean{
        //TODO
        if(viewModel.bookBean.isFromSDCard || !FunctionConfig.IS_ADVERT_ENABLED || VarConfig.ADVERT_READER_BANNER_INFO.type == AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED || UserInfoManager.isVip()) return false
        return true
    }

    private fun isShowRewardAdvert():Boolean{
        //TODO
        if(viewModel.bookBean.isFromSDCard || !FunctionConfig.IS_ADVERT_ENABLED || VarConfig.ADVERT_READER_CHAPTER_REWARD_INFO.type == AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED || UserInfoManager.isVip()) return false
        return true
    }

    private var mLastBannerView:View? = null

    private fun loadBannerAdvert(){
        //not show advert if is vip
        if(!isShowBannerAdvert()) return

        //TODO
        //LogUtil.log("loadBannerAdvert",System.currentTimeMillis())

        ViewHelper.setVisibility(true,databinding.bookreaderFlAdvertParent)

        AdvertCoverHelper.loadAdvertByCover(this,AdvertHelper.ADVERT_TYPE_BANNER,VarConfig.ADVERT_READER_BANNER_INFO,
            databinding.bookreaderFlAdvert,0f,object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                        databinding.bookreaderFlAdvert.removeAllViews()
                        databinding.bookreaderFlAdvert.addView(view)
                        mLastBannerView = view
                    }else{
                        if(databinding.bookreaderFlAdvert.childCount > 0){
                            mLastBannerView = databinding.bookreaderFlAdvert.getChildAt(0)
                        }
                    }
                }

                override fun onError(type: Int,code:Int,msg:String) {
                    if(databinding.bookreaderFlAdvert.childCount == 0 && mLastBannerView != null){
                        databinding.bookreaderFlAdvert.addView(mLastBannerView)
                    }
                }

                override fun onClose(type: Int) {
                    databinding.bookreaderFlAdvert.removeAllViews()
                }

            })


        //val marginRight = if(mIsShowBannerAdvertCloseBtn) 44 else 0
        //TODO
        /*val initDensity= AutoSizeConfig.getInstance().initDensity
        val adWidthCsj = (ScreenUtil.getScreenWidth()) / initDensity
        val adWidthGdt = (ScreenUtil.getScreenWidth()).toFloat()

        if(VarConfig.ADVERT_READER_BANNER_TYPE == VarConfig.ADVERT_TYPE_CSJ){
            loadBannerAdvertCsj(adWidthCsj){
                loadBannerAdvertGdt(adWidthGdt){}
            }
        }else if(VarConfig.ADVERT_READER_BANNER_TYPE == VarConfig.ADVERT_TYPE_GDT){
            loadBannerAdvertGdt(adWidthGdt){
                loadBannerAdvertCsj(adWidthCsj){

                }
            }
        }*/

    }

    /*private fun addBannerAdvertCloseBtn(parent:ViewGroup,view:View){
        if(view == null) return
        val lp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
        lp.gravity = Gravity.BOTTOM
        view.layoutParams = lp
        parent.removeAllViews()
        parent.addView(view)

        val initDensity= AutoSizeConfig.getInstance().initDensity
        val adWidth = ScreenUtil.getScreenWidth()/initDensity
        val adHeight = adWidth/6.4f

        val closeView = View(this@BookReadActivity)
        val closeLp = FrameLayout.LayoutParams(50.dp2px(),adHeight.dp2px().toInt())
        closeLp.gravity = Gravity.RIGHT
        closeView.layoutParams = closeLp
        closeView.setOnClickListener {
            parent.removeAllViews()
        }
        parent.addView(closeView)
    }*/

    /*private fun loadBannerAdvertCsj(adWidth: Float,onError: () -> Unit){
        AdvertHelper.loadBannerAdvert(this,VarConfig.ADVERT_READER_BANNER_CODE_ID_CSJ,adWidth,adWidth / 6.4f,object :
            INativeExpressAdListener{
            override fun onError(code: Int, msg: String) {
                onError()
            }

            override fun onNativeExpressAdLoad(adViews: List<Any>) {
                AdvertHelper.renderBannerAdvert_CSJ(this@BookReadActivity,adViews[0],object:AdvertHelper.IAdvertRenderListener{
                    override fun onAdClicked(view: View, p1: Int) {

                    }

                    override fun onAdShow(view: View, p1: Int) {

                    }

                    override fun onRenderFail(p0: View, p1: String, p2: Int) {
                        onError()
                    }

                    override fun onRenderSuccess(view: View, p1: Float, p2: Float) {
                        if(!mPageWidget.isChapterLastAdvertShowing()){
                            databinding.bookreaderFlAdvert.removeAllViews()
                            databinding.bookreaderFlAdvert.addView(view)
                        }
                        //addBannerAdvertCloseBtn(databinding.bookreaderFlAdvert, view)
                    }

                    override fun onDislikeReasonSelected(
                        position: Int,
                        value: String,
                        enforce: Boolean
                    ) {
                        databinding.bookreaderFlAdvert.removeAllViews()
                    }

                })
            }

        })
    }

    private fun loadBannerAdvertGdt(adWidth: Float,onError: () -> Unit){
        databinding.bookreaderFlAdvert.removeAllViews()

        AdvertHelper.loadBannerAdvert_GDT(this,VarConfig.ADVERT_READER_BANNER_CODE_ID_GDT,databinding.bookreaderFlAdvert,adWidth,adWidth / 6.4f, object:AdvertHelper.IUnifiedBannerADListenerGDT{
            override fun onError(code: Int, msg: String) {
                onError()
            }

            override fun onNoAD(code: Int, msg: String) {
                onError()
            }

            override fun onADReceive() {
                if(mPageWidget.isChapterLastAdvertShowing()){
                    databinding.bookreaderFlAdvert.removeAllViews()
                }
                //addBannerAdvertCloseBtn(databinding.bookreaderFlAdvertParent,databinding.bookreaderFlAdvert)
            }

            override fun onADExposure() {

            }

            override fun onADClosed() {
                databinding.bookreaderFlAdvert.removeAllViews()
            }

            override fun onADClicked() {

            }

            override fun onADLeftApplication() {

            }

        })

    }*/

    private fun setBarTextViewColor(color:Int){
        databinding.bookreaderTvPrePage.setTextColor(color)
        databinding.bookreaderTvNextPage.setTextColor(color)
        databinding.bookreaderTvCatalog.setTextColor(color)
        databinding.bookreaderTvSwitchMode.setTextColor(color)
        databinding.bookreaderTvSetting.setTextColor(color)
        databinding.includeSetting.bookreaderTvLiandu.setTextColor(color)
        databinding.includeSetting.bookreaderTvZiti.setTextColor(color)
        databinding.includeSetting.bookreaderTvBeijin.setTextColor(color)
        databinding.includeSetting.bookreaderTvFanye.setTextColor(color)
        databinding.includeSetting.bookreaderTvHangju.setTextColor(color)
        databinding.includeSetting.bookreaderTvXitong.setTextColor(color)
        databinding.includeSetting.bookreaderTvMoren.setTextColor(color)
        databinding.includeSetting.bookreaderTvFangzheng.setTextColor(color)
        databinding.includeSetting.bookreaderTvFugai.setTextColor(color)
        databinding.includeSetting.bookreaderTvPingyi.setTextColor(color)
        databinding.includeSetting.bookreaderBtnAddFontSize.setTextColor(color)
        databinding.includeSetting.bookreaderBtnSubFontSize.setTextColor(color)
        databinding.includeSetting.bookreaderTvFontSize.setTextColor(color)
    }

    private fun setBarContainerBorder(){

    }

    private fun addLiveDataObserve(){
        viewModel.fontSize.observe(this){fontSize->
            databinding.includeSetting.bookreaderTvFontSize.text=fontSize.toString()
            if(this::mPageWidget.isInitialized){
                mPageWidget.setFontSize(fontSize)
            }
        }

        viewModel.isDarkMode.observe(this){data->
            if(data){
                databinding.bookreaderTvSwitchMode.text="日间"
                //databinding.bookreaderTvProgress.setTextColor(Color.WHITE)
                //databinding.bookreaderTvTime.setTextColor(Color.WHITE)
                setBarTextViewColor(Color.WHITE)
                databinding.bookreaderFlRoot.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))
                databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))
                databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))

                databinding.bookreaderIvCatalog.setImageResource(R.mipmap.bookreader_icon_catalog_dark)
                databinding.bookreaderIvSwitchMode.setImageResource(R.mipmap.bookreader_icon_tolight)
                databinding.bookreaderIvSetting.setImageResource(R.mipmap.bookreader_icon_setting_dark)

                databinding.bookreaderCpb.setBackground(Color.parseColor("#4E4D4D"),Color.parseColor("#717171"))

                databinding.includeSetting.bookreaderLine1.setBackgroundColor(Color.parseColor("#383836"))
                databinding.includeSetting.bookreaderLine2.setBackgroundColor(Color.parseColor("#383836"))

                //databinding.includeSetting.bookreaderTvFontSize.setTextColor(Color.parseColor("#9F9F9F"))
                databinding.includeSetting.bookreaderBtnAddFontSize.setBtnBackgroundColor(Color.parseColor("#393837"))
                databinding.includeSetting.bookreaderBtnSubFontSize.setBtnBackgroundColor(Color.parseColor("#393837"))

                databinding.includeSetting.bookreaderCclBrightnessSystem.setBorder(Color.WHITE,1f.dp2px())
                databinding.includeSetting.bookreaderCclDefaultFontSize.setBorder(Color.WHITE,1f.dp2px())

                //databinding.bookreaderTvAddtoShelf.setTextColor(Color.WHITE)

                setFlipStyleBorder(viewModel.flipStyle.value!!)
                setLineSpaceRatioBorder(viewModel.lineSpaceRatio.value!!)

                mSlideFrag?.switchMode(true,5)

                databinding.includeSetting.bookreaderSeekbarBrightness.progressDrawable=resources.getDrawable(R.drawable.bookreader_seekbar_bg_dark,theme)

            }else{
                databinding.bookreaderTvSwitchMode.text="夜间"
                //databinding.bookreaderTvProgress.setTextColor(Color.BLACK)
                //databinding.bookreaderTvTime.setTextColor(Color.BLACK)
                setBarTextViewColor(Color.parseColor("#3D321C"))
                when(viewModel.mBgIdx){
                    1->{
                        databinding.bookreaderFlRoot.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color1))
                        databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color1))
                        databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color1))
                    }
                    2->{
                        databinding.bookreaderFlRoot.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color2))
                        databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color2))
                        databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color2))
                    }
                    3->{
                        databinding.bookreaderFlRoot.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color3))
                        databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color3))
                        databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color3))
                    }
                    4->{
                        databinding.bookreaderFlRoot.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color4))
                        databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color4))
                        databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color4))
                    }
                    5->{
                        databinding.bookreaderFlRoot.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color_dark))
                        databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color_dark))
                        databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))
                    }
                }


                databinding.bookreaderIvCatalog.setImageResource(R.mipmap.bookreader_icon_catalog)
                databinding.bookreaderIvSwitchMode.setImageResource(R.mipmap.bookreader_icon_todark)
                databinding.bookreaderIvSetting.setImageResource(R.mipmap.bookreader_icon_setting)

                databinding.bookreaderCpb.setBackground(Color.parseColor("#BCB8A6"),Color.parseColor("#A39D8A"))
                databinding.includeSetting.bookreaderLine1.setBackgroundColor(Color.parseColor("#BCB8A6"))
                databinding.includeSetting.bookreaderLine2.setBackgroundColor(Color.parseColor("#BCB8A6"))

                databinding.includeSetting.bookreaderBtnAddFontSize.setBtnBackgroundColor(Color.parseColor("#CECBBC"))
                databinding.includeSetting.bookreaderBtnSubFontSize.setBtnBackgroundColor(Color.parseColor("#CECBBC"))

                databinding.includeSetting.bookreaderCclBrightnessSystem.setBorder(Color.parseColor("#89817C"),1f.dp2px())
                databinding.includeSetting.bookreaderCclDefaultFontSize.setBorder(Color.parseColor("#89817C"),1f.dp2px())



                setFlipStyleBorder(viewModel.flipStyle.value!!)
                setLineSpaceRatioBorder(viewModel.lineSpaceRatio.value!!)
                mSlideFrag?.switchMode(false,viewModel.mBgIdx)

                databinding.includeSetting.bookreaderSeekbarBrightness.progressDrawable=resources.getDrawable(R.drawable.bookreader_seekbar_bg,theme)

            }
        }

        viewModel.flipStyle.observe(this){style->
           switchFlipStyle(style)
        }

        viewModel.lineSpaceRatio.observe(this){data->
         //  databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
          // databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#CECBBC"),0f)
          //  databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#CECBBC"),0f)

            setLineSpaceRatioBorder(data)
            if(this::mPageWidget.isInitialized){
                mPageWidget.setLineSpaceRatio(data)
            }
        }

        viewModel.isInBookShelf.observe(this){isInBookShelf->
            if(viewModel.bookBean.isFromSDCard) return@observe
            if(isInBookShelf){
                databinding.bookreaderLlAddtoShelf.visibility=View.GONE
            }else{
                if(databinding.bookreaderIvBack.visibility==View.VISIBLE){
                    databinding.bookreaderLlAddtoShelf.visibility=View.VISIBLE
                }else{
                    databinding.bookreaderLlAddtoShelf.visibility=View.GONE
                }
            }
        }

        viewModel.chapterListState.observe(this){data->
            if(!data){
                hideLoadingDialog()
                ToastUtil.show("加载书籍章节错误")
                databinding.bookreaderIvBack.visibility=View.VISIBLE
                if(!this::mPageWidget.isInitialized) return@observe
                mPageWidget.onLoadError()
            }else{

            }
        }

        viewModel.chapterContentState.observe(this){data->
            if(data){

            }else{
                //ToastUtil.show("加载书籍章节内容错误")
                //hideLoadingDialog()
                if(!this::mPageWidget.isInitialized) return@observe
                mPageWidget.onLoadError()
            }
        }

        viewModel.chapterContent.observe(this){data->
            //data maybe empty if cache
            var isJumpTo=false
            var chapter: Int
            var isJumpToEnd=viewModel.isJumpToEnd

            if(viewModel.isJumpTo!=null && viewModel.isJumpTo!!) {
                isJumpTo = true
            }
            if(viewModel.jumpToChapter!=null){
                chapter=viewModel.jumpToChapter!!
            }else{
                chapter=viewModel.currentChapter.value!!
            }
            showChapterRead(data,chapter,isJumpTo,isJumpToEnd,viewModel.jumpBeginPos,viewModel.jumpEndPos)
            if(isJumpToEnd){
                viewModel.isJumpToEnd=false
            }
            if(viewModel.jumpBeginPos>0){
                viewModel.jumpBeginPos=0
            }
            if(viewModel.jumpEndPos>0){
                viewModel.jumpEndPos=0
            }
            viewModel.isJumpTo=false
            //hideLoadingDialog()

        }

    }

    private fun setLineSpaceRatioBorder(ratio:Int){
        when(ratio){
            2->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
            3->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
            4->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
            5->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclLineSpace5.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace2.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace3.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclLineSpace4.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
        }
    }

    private fun setViewClickListener(){
        databinding.bookreaderIvMenu.setOnClickListener(this)
        databinding.bookreaderLlCatalog.setOnClickListener(this)
        databinding.bookreaderLlSwitchDayNight.setOnClickListener(this)
        databinding.bookreaderLlSetting.setOnClickListener(this)
        databinding.bookreaderTvPrePage.setOnClickListener(this)
        databinding.bookreaderTvNextPage.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclReaderBackgroundColor1.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclReaderBackgroundColor2.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclReaderBackgroundColor3.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclReaderBackgroundColor4.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclReaderBackgroundColorDark.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclFlipStyle3d.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclFlipStyleOverlap.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclFlipStyleTranslate.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclBrightnessSystem.setOnClickListener(this)
        databinding.includeSetting.bookreaderBtnSubFontSize.setOnClickListener(this)
        databinding.includeSetting.bookreaderBtnAddFontSize.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclDefaultFontSize.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclLineSpace2.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclLineSpace3.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclLineSpace4.setOnClickListener(this)
        databinding.includeSetting.bookreaderCclLineSpace5.setOnClickListener(this)
        databinding.bookreaderIvBack.setOnClickListener(this)
        databinding.bookreaderLlAddtoShelf.setOnClickListener(this)
        databinding.includeSetting.bookreaderFlBottombarSetting.setOnClickListener(this)
        databinding.bookreaderCatalogTop.setOnClickListener(this)
        databinding.bookreaderFlSlideParent.setOnClickListener(this)

    }

    private fun initSlide(list:MutableList<BookChapterCatalogBean.DataBean>){
        //set slide max height
        databinding.bookreaderFlSlide.layoutParams=databinding.bookreaderFlSlide.layoutParams.apply {
            this as LinearLayout.LayoutParams
            height=ScreenUtil.getScreenRealHeight()-74.dp2px()
        }

        mSlideFrag=BookReadSlideFragment()
        val bundle=Bundle()
        val cl=arrayListOf<BookChapterCatalogBean.DataBean>()
        for(item in list){
            cl.add(item)
        }
        bundle.putParcelableArrayList("chapters",cl)
        bundle.putParcelable("book",viewModel.bookBean)
        bundle.putBoolean("is_dark",viewModel.isDarkMode.value?:false)
        bundle.putInt("bg_idx",viewModel.mBgIdx)

        mSlideFrag!!.arguments=bundle
        mSlideFrag!!.setCloseListener {
            toggleBar()
        }
        supportFragmentManager.beginTransaction().replace(R.id.bookreader_fl_slide,mSlideFrag!!).commit()
    }

    /* public void mergeAllChapterToFile(){
        mPresenter.mergeAllBook(mBook,mChapterList);
    }*/

    private fun showChapterRead(data: String, chapter: Int,isJumpTo:Boolean,isJumpToEnd:Boolean,beginPos:Int=0,endPos:Int=0) {
        //save cache to local if from net
        if(data.isNotBlank()){
            CacheManager.getInstance().saveChapterFile(viewModel.bookBean.id, chapter, data,false)
        }

        if(!this::mPageWidget.isInitialized) return

        if(isJumpTo){
            if(isJumpToEnd){
                //mPageWidget.prePage()
                mPageWidget.pageToLast()
            }else{
                mPageWidget.jumpToChapter(chapter,false,beginPos,endPos)
            }
        }

        mPageWidget.onLoadSuccess()

    }

    private fun initPageWidget(){
        mIsDrawOnWord = viewModel.bookBean.isFromSDCard && viewModel.bookBean.path.endsWith("_en.txt")

        switchFlipStyle(viewModel.flipStyle.value!!)
    }

    private fun getReaderHeight():Int{
        var height = ScreenUtil.getScreenRealHeight()

        if(!viewModel.bookBean.isFromSDCard && !UserInfoManager.isVip() && FunctionConfig.IS_ADVERT_ENABLED){
            if(VarConfig.ADVERT_READER_BANNER_INFO.type != AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED){
                if(VarConfig.ADVERT_READER_BANNER_INFO.code_ids.csj.size > 0 && VarConfig.ADVERT_READER_BANNER_INFO.code_ids.csj[0].ar > 0f){
                    height = (ScreenUtil.getScreenRealHeight() - ScreenUtil.getScreenWidth() / VarConfig.ADVERT_READER_BANNER_INFO.code_ids.csj[0].ar).toInt()
                }else if(VarConfig.ADVERT_READER_BANNER_INFO.code_ids.gdt.size > 0 && VarConfig.ADVERT_READER_BANNER_INFO.code_ids.gdt[0].ar > 0f){
                    height = (ScreenUtil.getScreenRealHeight() - ScreenUtil.getScreenWidth() / VarConfig.ADVERT_READER_BANNER_INFO.code_ids.gdt[0].ar).toInt()
                }
            }
        }
        return height
    }

    private fun setPageWidget(style: Int) {
        var tmp=style
        if(style<1 || style>3) tmp=1

        if(viewModel.chapterList.value==null) return

        var width=ScreenUtil.getScreenWidth()
        val height = getReaderHeight()
        val isPreLoad = VarConfig.ADVERT_READER_CHAPTER_XXL_INFO.preload

        when (tmp) {
            1 -> mPageWidget =
                Read3DWidget(
                    this,
                    width,
                    height,
                    viewModel.bookBean.id,
                    this,
                    mIsDrawOnWord,
                    viewModel.bookBean.fontPath,
                    viewModel.bookBean.isFromSDCard,isPreLoad,
                    this
                )

            2 -> mPageWidget =
                OverlappedReadWidget(
                    this,
                    width,
                    height,
                    viewModel.bookBean.id,
                    this,
                    mIsDrawOnWord,
                    viewModel.bookBean.fontPath,
                    viewModel.bookBean.isFromSDCard,isPreLoad,
                    this
                )

            3 -> mPageWidget =
                TranslateReadWidget(
                    this,
                    width,
                    height,
                    viewModel.bookBean.id,
                    this,
                    mIsDrawOnWord,
                    viewModel.bookBean.fontPath,
                    viewModel.bookBean.isFromSDCard,isPreLoad,
                    this
                )
        }

        mPageWidget.setChapterList(viewModel.getChapterTitleList())
    }

    override fun onResume() {
        super.onResume()
        //checkTeenagerModeUseTime()
        viewModel.startReadTime=TimeUtil.getCurrentTimeSecond()
    }

    override fun onPause() {
        super.onPause()
        try{
            if(!this::mPageWidget.isInitialized) return
            if(TeenagerManager.isTeenagerMode)
                TeenagerManager.setLastUseTime()
            viewModel.endReadTime=TimeUtil.getCurrentTimeSecond()
            val readTime=viewModel.addBookTodayReadTime()
            viewModel.saveReadProgress(mPageWidget.currentBeginPos,mPageWidget.currentEndPos,mPageWidget.bufferLength)
            val value=(readTime shl 1) shr 1

            if(!viewModel.bookBean.isFromSDCard){
                ARouter.getInstance().build("/task/DailyTaskController").navigation()?.let {
                    it as IDailyTaskProvider
                    it.handleDailyTask(IDailyTaskProvider.DailyType.READ_TIME,value)
                }
            }

        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    private fun checkTeenagerModeUseTime() {
        if(viewModel.bookBean.isFromSDCard) return
        if (!TeenagerManager.isTeenagerMode) return
        if(mTeenagerInputPwdDialog!=null && mTeenagerInputPwdDialog!!.isShowing) return
        val useTime = TimeUtil.getCurrentTimeSecond().toInt() - TeenagerManager.getLastUseTime()
        TeenagerManager.addUseTime(useTime)
        if (TeenagerManager.useTime >= TeenagerManager.MAX_USE_TIME) {
            mTeenagerInputPwdDialog = InputDialog(this)
            mTeenagerInputPwdDialog!!.setDialogMsg("请输入青少年模式密码继续使用")
            mTeenagerInputPwdDialog!!.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD)
            mTeenagerInputPwdDialog!!.setCancelable(false)
            mTeenagerInputPwdDialog!!.setCanceledOnTouchOutside(false)
            mTeenagerInputPwdDialog!!.setCancelText("退出")
            mTeenagerInputPwdDialog!!.setOnCancelListener {
                ARouter.getInstance().build("/main/ClearToMainActivityImpl").navigation()?.let {
                    it as IClearToMainActivityProvider
                    it.clearToMain(true)
                }
                false
            }
            mTeenagerInputPwdDialog!!.setOnConfirmListener {
                if (mTeenagerInputPwdDialog!!.getInput() != "" && mTeenagerInputPwdDialog!!.getInput() == TeenagerManager.teenagerPwd) {
                    TeenagerManager.resetUseTime()
                    return@setOnConfirmListener true
                }
                ToastUtil.show("密码不正确")
                false
            }
            mTeenagerInputPwdDialog!!.show()
        }
    }

    //prevent memory leak
    companion object{
        private var readerReceiverWR:WeakReference<BookReadActivity>?=null

        class ReaderReceiver(ref:BookReadActivity):BroadcastReceiver(){
            init {
                readerReceiverWR=WeakReference(ref)
            }

            override fun onReceive(context: Context, intent: Intent) {
                val bookReadActivity=readerReceiverWR?.get()?:return
                if(!bookReadActivity::mPageWidget.isInitialized)return
                if (Intent.ACTION_BATTERY_CHANGED == intent.action) {
                    val level = intent.getIntExtra("level", 0)
                    bookReadActivity.mBatteryLevel=level
                    bookReadActivity.mPageWidget.setBattery(level)
                } else if (Intent.ACTION_TIME_TICK == intent.action) {
                    //bookReadActivity.databinding.bookreaderTvTime.text=TimeUtil.formatTimeHHmm(System.currentTimeMillis())
                    bookReadActivity.mPageWidget.setTime(TimeUtil.formatTimeHHmm(System.currentTimeMillis()))
                }
            }

        }

    }

    /*inner class ReaderReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (Intent.ACTION_BATTERY_CHANGED == intent.action) {
                val level = intent.getIntExtra("level", 0)
                mPageWidget.setBattery(100 - level)
            } else if (Intent.ACTION_TIME_TICK == intent.action) {
                mPageWidget.setTime(TimeUtil.formatTimeFullString(System.currentTimeMillis()))
            }
        }
    }*/


    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    private fun getChapterTitle(chapter:Int):String{
        return viewModel.chapterList.value!![chapter - 1].chapterTitle
    }

    override fun onChapterChanged(chapter: Int) {
        //TODO
        //LogUtil.log("onChapterChanged",System.currentTimeMillis())

        if(chapter < 1) return
        //LogUtil.log("onChapterChanged",mPageWidget,mPageWidget.currentBeginPos,mPageWidget.currentEndPos)
        //viewModel.saveReadProgress(mPageWidget.currentBeginPos,mPageWidget.currentEndPos)
        if(viewModel.chapterList.value==null) return
        if(viewModel.chapterList.value!!.size < chapter) return
        databinding.bookreaderTvTitle.text = getChapterTitle(chapter)
        checkTeenagerModeUseTime()
        //databinding.bookreaderCpb.setProgress(0)
        if(viewModel.chapterList.value!=null && viewModel.chapterList.value!!.size>0){
            //current chapter/total chapter
            val percent = chapter * 100*1.0f / viewModel.chapterList.value!!.size
            //val progress= StringUtil.float2PlainString(percent)
            //databinding.bookreaderTvProgress.text=progress+"%"
            databinding.bookreaderCpb.setProgress(percent.toInt())

        }

        //load advert when change chapter
        //AdvertHelper.loadBannerAdvert(this,this,this)
        //TODO
        /*if(this::mPageWidget.isInitialized && mPageWidget.isChapterLastAdvertShowing()){

        }else{
            loadBannerAdvert()
        }*/

        val readChapterCount=viewModel.addBookTodayReadChapterCount(chapter)
        val mode=(readChapterCount shr 31)
        val value=(readChapterCount shl 1) shr 1
        //LogUtil.log("onChapterChanged", readChapterCount,readChapterCount shr 31)
        if(!viewModel.bookBean.isFromSDCard && mode==-1){
            ARouter.getInstance().build("/task/DailyTaskController").navigation()?.let {
                it as IDailyTaskProvider
                it.handleDailyTask(IDailyTaskProvider.DailyType.READ_CHAPTER,value)
            }
        }

        viewModel.setCurrentChapter(chapter)

    }

    override fun onPageChanged(chapter: Int, page: Int) {
        //val progress=mPageWidget.currentEndPos * 100*1.0f / mPageWidget.bufferLength
        //databinding.bookreaderCpb.setProgress(progress.toInt())
        //viewModel.saveReadProgress(mPageWidget.currentBeginPos,mPageWidget.currentEndPos)
    }

    override fun onLoadChapterFailure(chapter: Int,isFromUser:Boolean,beginPos:Int,endPos:Int) {
        if(!BookUtil.isBookChapterFileExist(viewModel.bookBean.id,chapter)){
            if(isFromUser){
                //showLoadingDialog()
                //LogUtil.log("onLoadChapterFailure",chapter,viewModel.currentChapter.value)
                //jump to pre page last
                viewModel.isJumpTo=true
                viewModel.jumpToChapter=chapter
                if(viewModel.currentChapter.value!=null && chapter<viewModel.currentChapter.value!!){
                    viewModel.isJumpToEnd=true
                }else{
                    if(endPos>beginPos){
                        viewModel.jumpBeginPos=beginPos
                        viewModel.jumpEndPos=endPos
                    }
                }
            }else{
                viewModel.isJumpTo=false
            }

            viewModel.getChapterContent(chapter)
        }

    }


    override fun onCenterClick() {
        toggleBar()
    }

    private fun toggleBar(){
        if(databinding.bookreaderFlBottombar.visibility==View.VISIBLE){
            hideBar()
        }else{
            showBar()
        }
    }

    override fun onFlip() {
        hideBar()
    }

    private fun hideBar(){
        //databinding.bookreaderLlTopbar.visibility=View.GONE
        //databinding.bookreaderIvBack.visibility=View.INVISIBLE
       // databinding.bookreaderIvMenu.visibility=View.GONE
        databinding.bookreaderFlBottombar.visibility = View.GONE
        mShowSetting = false
        databinding.bookreaderCclBottombarProgress.visibility=View.VISIBLE
        databinding.includeSetting.bookreaderFlBottombarSetting.visibility=View.GONE
        databinding.bookreaderLlAddtoShelf.visibility=View.GONE
        databinding.bookreaderFlSlideParent.visibility=View.GONE
        if(viewModel.bookBean.isFromSDCard){
            ViewHelper.setVisibilityInvisible(false,databinding.bookreaderTvTitle)
            ViewHelper.setVisibilityInvisible(false,databinding.bookreaderIvBack)
        }
    }

    private fun showBar(){
        //databinding.bookreaderLlTopbar.visibility=View.VISIBLE
        //databinding.bookreaderIvMenu.visibility=View.VISIBLE
        //databinding.bookreaderIvBack.visibility=View.VISIBLE
        databinding.bookreaderFlBottombar.visibility=View.VISIBLE
        if(!viewModel.bookBean.isFromSDCard && !viewModel.isInBookShelf.value!!){
            databinding.bookreaderLlAddtoShelf.visibility=View.VISIBLE
        }
        ViewHelper.setVisibilityInvisible(true,databinding.bookreaderTvTitle)
        ViewHelper.setVisibilityInvisible(true,databinding.bookreaderIvBack)
    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.bookreader_iv_menu->{
                databinding.includeSetting.bookreaderFlBottombarSetting.visibility=View.GONE
                databinding.bookreaderCclBottombarProgress.visibility=View.VISIBLE
                if(databinding.bookreaderFlSlideParent.visibility==View.VISIBLE){
                    databinding.bookreaderFlBottombar.visibility=View.GONE
                    databinding.bookreaderFlSlideParent.visibility=View.GONE
                    databinding.bookreaderIvBack.visibility=View.INVISIBLE
                }else{
                    databinding.bookreaderFlBottombar.visibility=View.VISIBLE
                    databinding.bookreaderFlSlideParent.visibility=View.VISIBLE
                    databinding.bookreaderIvBack.visibility=View.VISIBLE
                }
            }
            R.id.bookreader_ll_catalog->{
                if(viewModel.bookBean.isFromSDCard){
                    val inputDialog = InputDialog(this)
                    inputDialog.setDialogTitle("跳转")
                    inputDialog.setDialogMsg("")
                    inputDialog.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL)
                    inputDialog.show()
                    inputDialog.setOnConfirmListener {
                        val p = inputDialog.getInput()
                        val beginPos = (p.toFloat() / 100 * mPageWidget.bufferLength).toInt()
                        mPageWidget.jumpToChapter(1,true,beginPos,beginPos+1)
                        true
                    }
                    return
                }
                databinding.includeSetting.bookreaderFlBottombarSetting.visibility=View.GONE
                databinding.bookreaderCclBottombarProgress.visibility=View.VISIBLE
                if(databinding.bookreaderFlSlideParent.visibility==View.VISIBLE){
                    databinding.bookreaderFlSlideParent.visibility=View.GONE
                }else{
                    databinding.bookreaderFlSlideParent.visibility=View.VISIBLE
                }
            }
            R.id.bookreader_catalog_top->{
                toggleBar()
            }
            R.id.bookreader_tv_prePage->{
                if(viewModel.currentChapter.value!!<=1) {
                    ToastUtil.show("没有上一章了")
                    return
                }
                //viewModel.setCurrentChapter(viewModel.currentChapter.value!!-1)
                mPageWidget.jumpToChapter(viewModel.currentChapter.value!!-1,true,0,0)
                //mPageWidget.prePage()
            }
            R.id.bookreader_tv_nextPage->{
                if(viewModel.currentChapter.value!!>=viewModel.chapterList.value!!.size) {
                    ToastUtil.show("没有下一章了")
                    return
                }
               // viewModel.setCurrentChapter(viewModel.currentChapter.value!!+1)
                mPageWidget.jumpToChapter(viewModel.currentChapter.value!!+1,true,0,0)
                //mPageWidget.nextPage()
            }
            R.id.bookreader_ll_switch_dayNight->{
                if(viewModel.isDarkMode.value!!){
                    toLightMode(viewModel.mBgIdx)
                }else{
                    toDarkMode()
                }

            }
            R.id.bookreader_ll_setting->{
                databinding.bookreaderFlSlideParent.visibility=View.GONE
                if(mShowSetting){
                    mShowSetting=false
                    databinding.bookreaderCclBottombarProgress.visibility=View.VISIBLE
                    databinding.includeSetting.bookreaderFlBottombarSetting.visibility=View.GONE
                }else{
                    mShowSetting=true
                    databinding.bookreaderCclBottombarProgress.visibility=View.GONE
                    databinding.includeSetting.bookreaderFlBottombarSetting.visibility=View.VISIBLE
                }

            }
            R.id.bookreader_ccl_reader_background_color1->{
                toLightMode(1)
            }
            R.id.bookreader_ccl_reader_background_color2->{
                toLightMode(2)
            }
            R.id.bookreader_ccl_reader_background_color3->{
                toLightMode(3)
            }
            R.id.bookreader_ccl_reader_background_color4->{
                toLightMode(4)
            }
            R.id.bookreader_ccl_reader_background_color_dark->{
                toDarkMode()
            }
            R.id.bookreader_ccl_flip_style_3d->{
                //save read progress before set flip style,because re-init reader page will read progress
                viewModel.saveReadProgress(mPageWidget.currentBeginPos,mPageWidget.currentEndPos,mPageWidget.bufferLength)
                viewModel.setFlipStyle(1)
            }
            R.id.bookreader_ccl_flip_style_overlap->{
                viewModel.saveReadProgress(mPageWidget.currentBeginPos,mPageWidget.currentEndPos,mPageWidget.bufferLength)
                viewModel.setFlipStyle(2)
            }
            R.id.bookreader_ccl_flip_style_translate->{
                viewModel.saveReadProgress(mPageWidget.currentBeginPos,mPageWidget.currentEndPos,mPageWidget.bufferLength)
                viewModel.setFlipStyle(3)
            }
            R.id.bookreader_ccl_brightness_system->{
                ScreenUtil.setAutoBrightness(this)
                databinding.includeSetting.bookreaderSeekbarBrightness.progress=0
            }
            R.id.bookreader_btn_sub_fontSize->{
               viewModel.addFontSize(-1)
                   //mPageWidget.setFontSize(viewModel.mFontSize)
                   //databinding.includeSetting.bookreaderTvFontSize.text=viewModel.mFontSize.toString()

            }
            R.id.bookreader_btn_add_fontSize->{
                viewModel.addFontSize(1)
                    //mPageWidget.setFontSize(viewModel.mFontSize)
                    //databinding.includeSetting.bookreaderTvFontSize.text=viewModel.mFontSize.toString()
            }
            R.id.bookreader_ccl_default_fontSize->{
                viewModel.setDefaultFontSize()
                //mPageWidget.setFontSize(viewModel.mFontSize)
            }
            R.id.bookreader_ccl_line_space2->{
                viewModel.setLineSpaceRatio(2)
            }
            R.id.bookreader_ccl_line_space3->{
                viewModel.setLineSpaceRatio(3)
            }
            R.id.bookreader_ccl_line_space4->{
                viewModel.setLineSpaceRatio(4)
            }
            R.id.bookreader_ccl_line_space5->{
                viewModel.setLineSpaceRatio(5)
            }
            R.id.bookreader_iv_back->{
                finish()
            }
            R.id.bookreader_ll_addto_shelf->{
                viewModel.addBookToShelf()
                ToastUtil.show("已添加到书架")
            }
        }
    }

    private fun setFlipStyleBorder(style:Int){
        when(style){
            1->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
            2->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
            3->{
                if(viewModel.isDarkMode.value!!){
                    databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#ffffff"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#383836"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#383836"),1f.dp2px())
                }else{
                    databinding.includeSetting.bookreaderCclFlipStyleTranslate.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyleOverlap.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                    databinding.includeSetting.bookreaderCclFlipStyle3d.setBorder(Color.parseColor("#CECBBC"),1f.dp2px())
                }

            }
        }
    }

    private fun switchFlipStyle(style:Int){
        setFlipStyleBorder(style)
        setPageWidget(style)
        setCurrentBg(viewModel.isDarkMode.value!!,viewModel.mBgIdx)
        //mPageWidget.setChapterList(viewModel.getChapterTitleList())
        mPageWidget.init(mCurrentBg,viewModel.readProgress)
        mPageWidget.setBattery(mBatteryLevel)
        mPageWidget.setFontSize(viewModel.fontSize.value!!)
        mPageWidget.setLineSpaceRatio(viewModel.lineSpaceRatio.value!!)
        if(viewModel.isDarkMode.value!!){
            toDarkMode()
        }else{
            toLightMode(viewModel.mBgIdx)
        }
        databinding.bookreaderFlReader.removeAllViews()
        databinding.bookreaderFlReader.addView(mPageWidget)
        //viewModel.setFlipStyle(style)
    }


    private fun toDarkMode(){
        setCurrentBg(true,5)
        databinding.includeSetting.bookreaderCclReaderBackgroundColorDark.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
        databinding.includeSetting.bookreaderCclReaderBackgroundColor1.setBorder(Color.TRANSPARENT,0f)
        databinding.includeSetting.bookreaderCclReaderBackgroundColor2.setBorder(Color.WHITE,1f.dp2px())
        databinding.includeSetting.bookreaderCclReaderBackgroundColor3.setBorder(Color.TRANSPARENT,0f)
        databinding.includeSetting.bookreaderCclReaderBackgroundColor4.setBorder(Color.TRANSPARENT,0f)
        mPageWidget.setBackgroundBitmap(mCurrentBg)
        mPageWidget.setTextColor(Color.WHITE,Color.WHITE)
        //cannot set bgIdx,because is useful when switch day mode
        //viewModel.setReadBackgroundIdx(5)
        viewModel.switchDarkMode(true)
        //setTopBarBackground()
    }

    /*private fun setTopBarBackground(){
        if(viewModel.isDarkMode.value!!){
            databinding.bookreaderLlTopbar.setBackgroundColor(Color.BLACK)
        }else{
            when(viewModel.mBgIdx){
                1->{
                    databinding.bookreaderLlTopbar.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color1))
                }
                2->{
                    databinding.bookreaderLlTopbar.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color2))
                }
                3->{
                    databinding.bookreaderLlTopbar.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color3))
                }
                4->{
                    databinding.bookreaderLlTopbar.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color4))
                }
                5->{
                    databinding.bookreaderLlTopbar.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))
                }
            }
        }
    }*/

    //5 is dark mode
    private fun toLightMode(idx:Int){
        if(idx<5)
            setCurrentBg(false,idx)
        else
            setCurrentBg(true,idx)

        when(idx){
            1->{
                databinding.includeSetting.bookreaderCclReaderBackgroundColor1.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor2.setBorder(Color.WHITE,1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor3.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColor4.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColorDark.setBorder(Color.TRANSPARENT,0f)
                databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color1))
                databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color1))
                mPageWidget.setBackgroundBitmap(mCurrentBg)
                mPageWidget.setTextColor(Color.BLACK,Color.BLACK)
                viewModel.setReadBackgroundIdx(1)
                viewModel.switchDarkMode(false)
                //setTopBarBackground()
            }
            2->{
                databinding.includeSetting.bookreaderCclReaderBackgroundColor2.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor1.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColor3.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColor4.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColorDark.setBorder(Color.TRANSPARENT,0f)
                databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color2))
                databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color2))
                mPageWidget.setBackgroundBitmap(mCurrentBg)
                mPageWidget.setTextColor(Color.BLACK,Color.BLACK)
                viewModel.setReadBackgroundIdx(2)
                viewModel.switchDarkMode(false)
                //setTopBarBackground()
            }
            3->{
                databinding.includeSetting.bookreaderCclReaderBackgroundColor3.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor1.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColor2.setBorder(Color.WHITE,1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor4.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColorDark.setBorder(Color.TRANSPARENT,0f)
                databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color3))
                databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color3))
                mPageWidget.setBackgroundBitmap(mCurrentBg)
                mPageWidget.setTextColor(Color.BLACK,Color.BLACK)
                viewModel.setReadBackgroundIdx(3)
                viewModel.switchDarkMode(false)
                //setTopBarBackground()
            }
            4->{
                databinding.includeSetting.bookreaderCclReaderBackgroundColor4.setBorder(Color.parseColor("#4C432F"),1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor1.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColor2.setBorder(Color.WHITE,1f.dp2px())
                databinding.includeSetting.bookreaderCclReaderBackgroundColor3.setBorder(Color.TRANSPARENT,0f)
                databinding.includeSetting.bookreaderCclReaderBackgroundColorDark.setBorder(Color.TRANSPARENT,0f)
                databinding.bookreaderLlBottombar.setBackgroundColor(ColorUtil.getResourceColor(this@BookReadActivity,R.color.read_background_color4))
                databinding.includeSetting.bookreaderLlBottombarSetting.setBackgroundColor(ColorUtil.getResourceColor(this,R.color.read_background_color4))
                mPageWidget.setBackgroundBitmap(mCurrentBg)
                mPageWidget.setTextColor(Color.BLACK,Color.BLACK)
                viewModel.setReadBackgroundIdx(4)
                viewModel.switchDarkMode(false)
                //setTopBarBackground()
            }
            5->{
                toDarkMode()
            }

        }

        mSlideFrag?.switchMode(viewModel.isDarkMode.value?:false,viewModel.mBgIdx)

    }

    private fun setCurrentBg(isDark:Boolean,idx:Int) {
        if(isDark){
            mCurrentBg=ColorUtil.color2ScreenBitmap(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))
            return
        }
        when (idx) {
            1 -> {
                mCurrentBg=ColorUtil.color2ScreenBitmap(ColorUtil.getResourceColor(this,R.color.read_background_color1))
            }
            2 -> {
                mCurrentBg=ColorUtil.color2ScreenBitmap(ColorUtil.getResourceColor(this,R.color.read_background_color2))
            }
            3 -> {
                mCurrentBg=ColorUtil.color2ScreenBitmap(ColorUtil.getResourceColor(this,R.color.read_background_color3))
            }
            4 -> {
                mCurrentBg=ColorUtil.color2ScreenBitmap(ColorUtil.getResourceColor(this,R.color.read_background_color4))
            }
            5 -> {
                mCurrentBg=ColorUtil.color2ScreenBitmap(ColorUtil.getResourceColor(this,R.color.read_background_color_dark))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        try{
            EventBus.getDefault().unregister(this)
            unregisterReceiver(mReceiver)
            //mTTAd?.setExpressInteractionListener(null)
            //mTTAd?.destroy()
            AdvertHelper.destroy()
            mBannerAdvertCountDownDispose?.dispose()
            //clear cache when exit but not download book
            databinding.bookreaderFlAdvert.removeAllViews()
            if(!viewModel.bookBean.isFromSDCard && !viewModel.hasBookDownloaded()){
                val bookDir=FileUtils.getBookDir(viewModel.bookBean.id)
                FileUtil.deleteFileOrDirectory(bookDir)
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        UMengHelper.onUMEvent(LibraryCommon.getContext(),"page_bookreader_exit")
    }

    //brightness seekbar
    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        if(fromUser)
            ScreenUtil.setScreenBrightness(this,progress/100f)
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {

    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {

    }

    @Subscribe
    fun onInBookShelfEvent(event:InBookShelfEvent){
        if(event.bookId==viewModel.bookBean.id){
            viewModel.isInBookShelf.value=event.isInBookShelf
        }
    }

    override fun isShowChapterAdvert(): Boolean {
        var isShowChapterLastAdvert = false

        if(!viewModel.bookBean.isFromSDCard && !UserInfoManager.isVip() && FunctionConfig.IS_ADVERT_ENABLED){
            if(VarConfig.ADVERT_READER_CHAPTER_XXL_INFO.type != AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED){
                isShowChapterLastAdvert = true
            }
        }
        return isShowChapterLastAdvert
    }

    override fun getChapterAdvertView(curChapter:Int,listener:IOnGetChapterAdvertView){
        //TODO
        loadChapterLastXxlAdvert(curChapter,listener)

        //loadChapterLastTestAdvert(listener)
    }

    private fun loadChapterLastTestAdvert(listener:IOnGetChapterAdvertView){
        val view = View(this)
        view.setBackgroundColor(Color.GREEN)
        val lp = FrameLayout.LayoutParams(300.dp2px(),300.dp2px())
        lp.gravity = Gravity.CENTER
        view.layoutParams = lp
        view.setOnClickListener {
            //ToastUtil.show("aaa")
        }

        val fl = BookReaderChapterAdvertContainerView(this)
        //fl.setBackgroundColor(Color.RED)
        val flLp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT)
        flLp.topMargin = StatusBarUtil.getStatusBarHeight(this) + HeaderBarView.DEFAULT_HEIGHT
        fl.layoutParams = flLp
        fl.setOnDispatchTouchEventListener(object : BookReaderChapterAdvertContainerView.IOnDispatchTouchEventListener{
            override fun onActionDown(x:Float,y:Float) {
                mPageWidget.handleActionDown(x,y)
            }

            override fun onActionMove(x:Float,y:Float) {
                mPageWidget.handleActionMove(x,y)
            }

            override fun onActionUp() {
                mPageWidget.handleActionUp(false)
            }

            override fun onActionCancel() {
                mPageWidget.handleActionCancel()
            }

        })

        fl.addView(view)

        listener.onSuccess(fl)
    }

    private fun loadChapterLastXxlAdvert(curChapter: Int,listener:IOnGetChapterAdvertView){
        listener.onSuccess(addChapterAdvertViewPlaceHolder())

        AdvertCoverHelper.loadAdvertByCover(this,AdvertHelper.ADVERT_TYPE_XXL,VarConfig.ADVERT_READER_CHAPTER_XXL_INFO,
            null,0f,object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    if(view == null) return
                    updateChapterAdvertViewWhenLoadSuccess(view)
                }

                override fun onError(type: Int,code:Int,msg:String) {
                    mPageWidget.skipPageLastAdvert()
                }

                override fun onClose(type: Int) {
                    mPageWidget.skipPageLastAdvert()
                }

            })
    }

    private var mBrclacv:BookReaderChapterAdvertContainerView? = null
    private var mTvCountDown:TextView? = null

    private fun addChapterAdvertViewPlaceHolder():View{
        val fl = BookReaderChapterAdvertContainerView(this)
        //TODO
        //fl.setBackgroundColor(Color.RED)
        val topMargin = StatusBarUtil.getStatusBarHeight(this) + HeaderBarView.DEFAULT_HEIGHT
        val flLp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT)
        flLp.topMargin = topMargin
        fl.layoutParams = flLp

        fl.setOnDispatchTouchEventListener(object : BookReaderChapterAdvertContainerView.IOnDispatchTouchEventListener{
            override fun onActionDown(x:Float,y:Float) {
                mPageWidget.handleActionDown(x,y)
            }

            override fun onActionMove(x:Float,y:Float) {
                mPageWidget.handleActionMove(x,y)
            }

            override fun onActionUp() {
                mPageWidget.handleActionUp(false)
            }

            override fun onActionCancel() {
                mPageWidget.handleActionCancel()
            }

        })

        if(mPageWidget.isShowChapterLastAdvertCountDown){
            mTvCountDown = TextView(this)
            val tvLp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
            tvLp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM
            tvLp.bottomMargin = 60.dp2px()
            mTvCountDown!!.layoutParams = tvLp
            mTvCountDown!!.textSize = 14f
            mTvCountDown!!.text = "${mPageWidget._CHAPTER_ADVERT_COUNT_DOWN_SECOND}秒后，滑动可继续阅读"
            fl.addView(mTvCountDown)
        }

        //TODO
        if(VarConfig.ADVERT_READER_CHAPTER_REWARD_INFO.type != AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED){
            fl.addView(getRewardTipView())
        }

        mBrclacv = fl

        return fl
    }

    private fun getRewardTipView():View{
        val tvRewardTip = TextView(this)
        val tvRewardLp = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
        tvRewardTip!!.layoutParams = tvRewardLp
        tvRewardTip!!.textSize = 14f
        tvRewardTip!!.text = "看小视频最高"

        val tvRewardTip2 = TextView(this)
        val tvRewardLp2 = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
        tvRewardTip2!!.layoutParams = tvRewardLp2
        tvRewardTip2!!.textSize = 14f
        tvRewardTip2!!.text = "领取100金币"
        tvRewardTip2.setPaintFlags(tvRewardTip2.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)
        tvRewardTip2.setTextColor(Color.RED)

        val llRewardTip = LinearLayout(this)
        llRewardTip.orientation = LinearLayout.HORIZONTAL
        val llRewardTipLp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
        tvRewardLp.bottomMargin = 20.dp2px()
        llRewardTipLp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM
        llRewardTip.layoutParams = llRewardTipLp

        llRewardTip.addView(tvRewardTip)
        llRewardTip.addView(tvRewardTip2)
        llRewardTip.setOnClickListener {
            loadRewardAdvert()
        }
        return llRewardTip
    }

    private var mPageLastAdvertViewCountDown = 0

    private fun updateChapterAdvertViewWhenLoadSuccess(view:View){
        if(mBrclacv == null) return
        mBrclacv!!.removeAllViews()
        //view.setBackgroundColor(Color.GREEN)
        val lp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
        //TODO
        //lp.topMargin = -20.dp2px()
        view.layoutParams = lp
        mBrclacv!!.addView(view)
        if(mPageWidget.isShowChapterLastAdvertCountDown){
            mTvCountDown = TextView(this)
            val tvLp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)
            tvLp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM
            tvLp.bottomMargin = 60.dp2px()
            mTvCountDown!!.layoutParams = tvLp
            mTvCountDown!!.textSize = 14f
            var str = "滑动可继续阅读"
            if(mPageLastAdvertViewCountDown > 0){
                str = "${mPageLastAdvertViewCountDown}秒后，滑动可继续阅读"
            }
            mTvCountDown!!.text =  str
            mBrclacv!!.addView(mTvCountDown)
        }

        if(VarConfig.ADVERT_READER_CHAPTER_REWARD_INFO.type!= AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED){
            mBrclacv!!.addView(getRewardTipView())
        }
    }

    private fun onRewardAdvertWatchCompleted(){
        TodayWatchRewardAdvertCountDaoManager.addTodayWatchAdvertCount()

        if(UserInfoManager.checkLogin()){
            viewModel.completedRewardTask()
        }else{
            var rewardWatchCount = SharedPreferenceHelper.getInt("reader","reward_watch_count",0)
            SharedPreferenceHelper.setInt("reader","reward_watch_count",rewardWatchCount + 1)
        }
    }

    private fun loadRewardAdvert(){
        if(!isShowRewardAdvert()) return

        AdvertCoverHelper.loadAdvertByCover(this,AdvertHelper.ADVERT_TYPE_REWARD,VarConfig.ADVERT_READER_CHAPTER_REWARD_INFO,
            null,0f,object :AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    onRewardAdvertWatchCompleted()
                }

                override fun onError(type: Int,code:Int,msg:String) {
                    ToastUtil.show("加载视频广告失败")
                }

                override fun onClose(type: Int) {

                }

            })
    }

    override fun onShowChapterAdvert() {
        //ViewHelper.setVisibility(false,databinding.bookreaderTvTitle)
        databinding.bookreaderTvTitle.text = "广告是为了更好地支持作者"
        ViewHelper.setVisibility(false,databinding.bookreaderIvMenu)
        ViewHelper.setVisibility(false,databinding.bookreaderLlAddtoShelf)
        if(isShowBannerAdvert()){
            //hideBannerAdvert()
            ViewHelper.setVisibility(false,databinding.bookreaderFlAdvertParent)
            mPageWidget.setCanvasHeight(ScreenUtil.getScreenRealHeight())
        }

    }

    override fun onHideChapterAdvert() {
        //ViewHelper.setVisibility(true,databinding.bookreaderTvTitle)
        if(viewModel.currentChapter.value != null)
            databinding.bookreaderTvTitle.text = getChapterTitle(viewModel.currentChapter.value!!)
        ViewHelper.setVisibility(true,databinding.bookreaderIvMenu)
        //if(viewModel.isInBookShelf.value != null)
            //ViewHelper.setVisibility(!viewModel.isInBookShelf.value!!,databinding.bookreaderLlAddtoShelf)
        if(isShowBannerAdvert()){
            //loadBannerAdvert()
            ViewHelper.setVisibility(true,databinding.bookreaderFlAdvertParent)
            mPageWidget.setCanvasHeight(getReaderHeight())
        }
    }

    override fun onChapterAdvertCountDown(countdown: Int) {
        mPageLastAdvertViewCountDown = countdown
        mTvCountDown?.let{
            if(countdown > 0){
                it.text =  "${countdown}秒后，滑动可继续阅读"
            }else{
                it.text = "滑动可继续阅读"
            }
        }
    }


}